package com.tdx.blog_nowcoder.service;


import com.tdx.blog_nowcoder.constant.ActivateConstant;
import com.tdx.blog_nowcoder.dao.LoginTicketMapper;
import com.tdx.blog_nowcoder.dao.UserMapper;
import com.tdx.blog_nowcoder.entity.LoginTicket;
import com.tdx.blog_nowcoder.entity.User;
import com.tdx.blog_nowcoder.utils.MailClient;
import com.tdx.blog_nowcoder.utils.RandomUUID;
import com.tdx.blog_nowcoder.utils.RedisKeyUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.tdx.blog_nowcoder.constant.UserRoleConstant.ROLE_USER;
import static com.tdx.blog_nowcoder.constant.UserRoleConstant.ROLE_ADMIN;
import static com.tdx.blog_nowcoder.constant.UserRoleConstant.ROLE_UP;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LoginTicketMapper loginTicketMapper;

    @Autowired
    private MailClient mailClient;

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private RedisTemplate redisTemplate;


    @Value("${project.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    //@Cacheable(value = "user",key = "#id")
    public User selectUserById(int id){
        //User user = getUserFromCache(id); // 缓存取值
//        if(user==null){
//            user = initCache(id);
//        }
        //从数据库中查找
        User user = userMapper.selectUserById(id);

        return user;
    //  return userMapper.selectUserById(id);
    }

    @CacheEvict(cacheNames = "user",key = "#id")
    public int deleteUserById(int id){
        int rows = userMapper.deleteUserById(id);
        return rows;
    }

    public Map<String,Object> registerUser(User user){
        Map<String,Object> map = new HashMap<>();
        if(user==null){
            throw new IllegalArgumentException("参数不能为空!");
        }
        if(StringUtils.isBlank(user.getUsername())){
            map.put("usernameMsg", "账号不能为空!");
            return map;
        }
        if(StringUtils.isBlank(user.getPassword())){
            map.put("passwordMsg", "密码不能为空!");
            return map;
        }
        if(StringUtils.isBlank(user.getEmail())){
            map.put("emailMsg", "邮箱不能为空!");
            return map;
        }
        // 验证账号
        User u = userMapper.selectUserByName(user.getUsername());
        if (u != null) {
            map.put("usernameMsg", "该账号已存在!");
            return map;
        }
        //注册账户,设置其他属性值
        user.setSalt(RandomUUID.getUUID().substring(1,6));
        user.setPassword(RandomUUID.md5(user.getPassword()+user.getSalt()));
        user.setType(0);//普通用户
        user.setStatus(0);//未激活状态

        user.setActivationCode(RandomUUID.getUUID());
        user.setCreateTime(new Date());

        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));

        //执行sql
        userMapper.insertUser(user);

        // 发送激活邮件通知
        Context context = new Context();
        context.setVariable("username",user.getUsername());

        // http://localhost:8080/community/activation/101/code
        String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
        //System.out.println(url);
        context.setVariable("url", url);
        String content = templateEngine.process("/mail/activation", context);
        mailClient.sendMail(user.getEmail(), "激活账号", content);

        return map;
    }


    //激活用户
    public int activateUser(int userID,String code){
        if(StringUtils.isBlank(code)){
            return ActivateConstant.ACTIVATION_FAILURE;
        }
        User user = userMapper.selectUserById(userID);
        if(user==null){
            return ActivateConstant.ACTIVATION_FAILURE;
        }else if(user.getStatus()==1){ // 已经激活
            return ActivateConstant.ACTIVATION_REPEAT;
        }else {
            userMapper.updateUserStatus(userID, 1);
            //用户状态改变需要清空缓存
            clearCache(userID);
            return ActivateConstant.ACTIVATION_SUCCESS;
        }


    }


    public Map<String,Object> validLogin(String username,String password,int expiredSeconds){
        Map<String,Object> map = new HashMap<>();
        // 空值处理
        if (StringUtils.isBlank(username)) {
            map.put("usernameMsg", "账号不能为空!");
            return map;
        }
        if (StringUtils.isBlank(password)) {
            map.put("passwordMsg", "密码不能为空!");
            return map;
        }
        // 验证账号
        User user = userMapper.selectUserByName(username);
        if (user == null) {
            map.put("usernameMsg", "该账号不存在!");
            return map;
        }

        // 验证状态
        if (user.getStatus() == 0) {
            map.put("usernameMsg", "该账号未激活!");
            return map;
        }

        // 验证密码
        password = RandomUUID.md5(password + user.getSalt());
        if (!user.getPassword().equals(password)) {
            map.put("passwordMsg", "密码不正确!");
            return map;
        }
        //验证通过，生成ticket凭证
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(user.getId());
        loginTicket.setTicket(RandomUUID.getUUID());
        loginTicket.setStatus(0);
        loginTicket.setExpired(new Date(System.currentTimeMillis() + expiredSeconds * 1000));

        //将登入凭证改为存入redis
//        loginTicketMapper.insertLoginTicket(loginTicket);
        String ticketRediskey = RedisKeyUtils.getLoginTicketKey(loginTicket.getTicket());
        //将对象存入redis
        redisTemplate.opsForValue().set(ticketRediskey, loginTicket);



        map.put("ticket",loginTicket.getTicket()); // 生成随机票据
        return map;
    }

    public  LoginTicket findLoginTicket(String ticket){
        String loginTicketKey = RedisKeyUtils.getLoginTicketKey(ticket);
//        return loginTicketMapper.selectByTicket(ticket);
        return (LoginTicket) redisTemplate.opsForValue().get(loginTicketKey);
    }

    public void logout(String ticket){
        //更新缓存就是取出来修改再存一遍
        String loginTicketKey = RedisKeyUtils.getLoginTicketKey(ticket);
        LoginTicket new_ticket = (LoginTicket) redisTemplate.opsForValue().get(loginTicketKey);
        new_ticket.setStatus(1);
        redisTemplate.opsForValue().set(loginTicketKey, new_ticket);
//        loginTicketMapper.updateStatus(ticket, 1);
    }


    public int updateHeader(int userId,String headUrl){
        // userMapper.updateUserHeader(userId,headUrl);
        int rows = userMapper.updateUserHeader(userId,headUrl);
        clearCache(userId);
        return rows;
    }

    public User findUserByName(String username){
        return userMapper.selectUserByName(username);
    }

    //从缓存中取数据
    public User getUserFromCache(int userId){
        String userKey = RedisKeyUtils.getUserKey(userId);
        return (User) redisTemplate.opsForValue().get(userKey);
    }

    // 初始化用户数据的缓存
    public User initCache(int userId){
        //从数据库中查找
        User user = userMapper.selectUserById(userId);
        if(user!=null){
            String userKey = RedisKeyUtils.getUserKey(userId);
            //存入redis数据库
            redisTemplate.opsForValue().set(userKey,user,3600, TimeUnit.SECONDS);
            return user;
        }else {
            return null;
        }
    }
    // 清除缓存中的数据

    public void clearCache(int userId){
        String userKey = RedisKeyUtils.getUserKey(userId);
        redisTemplate.delete(userKey);
    }


    //添加用户权限
    public Collection<? extends GrantedAuthority> getUserAuthorities(int userId){
        User user = selectUserById(userId);
        List<GrantedAuthority> authorityList = new ArrayList<>();
        authorityList.add(new GrantedAuthority() {
            @Override
            public String getAuthority() {
                switch (user.getType()){
                    case 1: //1 为管理员
                        return ROLE_ADMIN;
                    case 2:
                        return ROLE_UP;
                    default:
                        return ROLE_USER;
                }
            }
        });
        return authorityList;
    }




}
